import React, { useEffect } from 'react';
import TRNotification from '@/utils/notification';
import styles from './index.less';
import { Button, Input, Modal, Select, Space, Table } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import moment from 'moment';
import { SearchOutlined } from '@/utils/antdIcons';
import { queryMarketList } from '../../../../services';
import { useSetState } from 'ahooks';
import { PageLoading, TRMessage } from '@/components';
import { getTreeByCodes } from '@/utils';
import { HttpCode } from '@/utils/contacts';
import { arrToObj } from '../../helper';
import { citeContractFn, getContractTimeByCite } from '../../../../services';

const CiteTemplateComponent = ({ onClose, pageQuery = {}, menuCode, setTableData }) => {
  const [state, setSate] = useSetState({
    loading: true,
    stationIds: [],
    options: [],
    contractName: '',
    tableLoading: false,
    dataSource: [],
  });

  useEffect(() => {
    fetch();
  }, []);

  const fetch = async () => {
    let stationIds = [];
    const res = await queryMarketList(menuCode);
    if (res.statusCode === HttpCode.SUCCESS) {
      const { treeOptions: value, allKeys: ids } = getTreeByCodes(['station'], res.json);
      stationIds = ids;
      setSate({
        options: value,
        stationIds: ids,
      });
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
    setSate({
      loading: false,
    });
    await search(stationIds, state.contractName);
  };

  const handleCancel = () => {
    onClose();
  };

  const changeStationIds = (v) => {
    setSate({
      stationIds: v,
    });
  };

  const search = async (stationIds = [], contractName = '') => {
    setSate({
      tableLoading: true,
    });
    const res = await citeContractFn({
      contractName,
      startDate: moment(pageQuery?.st || '').format('YYYY-MM-DD') || '',
      endDate: moment(pageQuery?.en || '').format('YYYY-MM-DD') || '',
      stationIds,
    });
    if (res.statusCode === HttpCode.SUCCESS) {
      let arr = res?.dataList || [];
      arr = arr?.map((i, k) => ({ ...i, key: 'l' + k }));
      setSate({
        dataSource: arr,
      });
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
    setSate({
      tableLoading: false,
    });
  };

  const changeContractName = (e) => {
    setSate({
      contractName: e.target.value,
    });
  };

  const _getTitle = () => {
    return (
      <Space size={16}>
        <span>引用合约</span>
        <span>
          {moment(pageQuery?.st).format('YYYYMMDD')}-{moment(pageQuery?.en).format('YYYYMMDD')}
        </span>
      </Space>
    );
  };

  const _getHead = () => {
    const width = 230;
    return (
      <div className={styles.head}>
        <Space size={16}>
          <Select
            maxTagCount={1}
            style={{ width }}
            options={state.options}
            mode="multiple"
            maxTagTextLength={7}
            showArrow={true}
            onChange={changeStationIds}
            value={state.stationIds}
            placeholder="全部结算单元"
          />
          <Input
            suffix={<SearchOutlined />}
            placeholder={'搜索'}
            style={{ width }}
            value={state.contractName}
            onChange={changeContractName}
          />
        </Space>
        <Button type={'primary'} onClick={() => search(state.stationIds, state.contractName)}>
          查询
        </Button>
      </div>
    );
  };

  const _getTable = () => {
    return (
      <Table
        className={styles.table}
        size={'small'}
        locale={tableLocale}
        loading={state.tableLoading}
        scroll={{
          y: 370,
          height: 370,
        }}
        pagination={false}
        columns={columns}
        rowKey={'key'}
        dataSource={state.dataSource}
      />
    );
  };

  const handleQuote = (v) => {
    Modal.confirm({
      style: { top: '30%' },
      title: '确认引用' + v.contractName + '合约?',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        setTableData({
          loading: true,
        });
        const params = { ...v, startDate: pageQuery.st, endDate: pageQuery.en };
        const res = await getContractTimeByCite(params);
        if (res.statusCode === HttpCode.SUCCESS) {
          let arr = res?.results || [];
          arr = arr?.map((i) => ({ ...i, id: i.key }));
          const obj = arrToObj(arr);
          setTableData({
            dataSourceObj: obj,
          });
          handleCancel();
        } else {
          TRMessage.error(res?.message || '系统异常');
        }
        setTableData({
          loading: false,
        });
      },
    });
  };

  const columns = [
    { dataIndex: 'contractName', title: '  合约名称', width: '220px', align: 'left' },
    { dataIndex: 'quantity', title: '电量', width: '50px', align: 'center' },
    { dataIndex: 'price', title: '电价', width: '50px', align: 'center' },
    {
      dataIndex: 'caozuo',
      title: '操作',
      width: '30px',
      align: 'center',
      render: (v, record) => <a onClick={() => handleQuote(record)}>引用</a>,
    },
  ];

  return (
    <Modal
      className={styles.modal}
      visible={true}
      onCancel={handleCancel}
      width={'850px'}
      maskClosable={false}
      title={_getTitle()}
      centered
      footer={null}
    >
      {state.loading ? (
        <PageLoading />
      ) : (
        <>
          {_getHead()}
          {_getTable()}
        </>
      )}
    </Modal>
  );
};

class CiteTemplateModal {
  __key__ = '';
  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <CiteTemplateComponent
            {...props}
            onClose={() => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve();
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new CiteTemplateModal();
